<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
use Aliyun\Core\Config;
use Aliyun\Core\Profile\DefaultProfile;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
//use think\cache\driver\Memcache;
use OSS\OssClient;
use think\DB;

function rand_movie($num=6){

    $tuijian = Db::name('movie')->field('id,image,movie_name')->where('id >= (SELECT floor(RAND() * (SELECT MAX(id) FROM `movie`))) ')->limit($num)->select();

    return $tuijian;
}

//获取抖音用户信息
function get_dy_user(){
    $url = 'https://open.douyin.com/oauth/access_token/?client_key='.config('api.dy_key').'&client_secret='.config('api.dy_secret').'&grant_type=authorization_code&code='.input('code');

    $res = json_decode(curl_get($url),true);

    if(!empty($res['data']['open_id'])){
        $token =  $res['data']['access_token'];

        $url = 'https://open.douyin.com/oauth/userinfo/?access_token='.$token.'&open_id='.$res['data']['open_id'];

        $res = json_decode(curl_get($url),true);

        return $res;

    }else{
        redirect(url('/'));
    }


}


//订单号
function create_order_sn()
{
    return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}

//判断是否微信浏览器
function isWeixin()
{
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
        return true;
    }
    return false;
}


//所有类型
function getTypes(){
    //所有类型
    $types = Db::name('movie_type')->field('id,type_name')->order('rank_main desc,id desc')->select();

    return $types;

}

//底部固定课程

function menuLesson()
{

    $bottom_menu = DB::name('movie a')->leftJoin('config b', 'a.id=b.value')
        ->where("b.key='bottom_menu'")
        ->field('a.id,a.movie_name')->find();

    if (!$bottom_menu) {
        $bottom_menu = ['movie_name' => '电影中心', 'id' => 0];
    }

    return $bottom_menu;

}


/**
 * 短信发送
 * @param $to    接收人
 * @param $model    短信模板ID
 * @param $code   短信验证码
 * @return json
 * @说明：有优惠，先领卷在购买，不谢！https://promotion.aliyun.com/ntms/yunparter/invite.html?userCode=ob1nyal1
 */
function send_sms($to, $model, $code)
{
    require_once '../extend/aliyun_sms/vendor/autoload.php';
    Config::load(); //加载区域结点配置
//    $config = '根据你的实际情况读取配置文件或读取数据库，本项目是将配置写入数据库实现';
    $accessKeyId = config('aliyun.sms.accessKeyId');
    $accessKeySecret = config('aliyun.sms.accessKeySecret');
    $templateParam = $code;
    //短信签名
    $signName = '掌间创课';
    //短信模板ID
    switch ($model) {
        case 1:
            $templateCode = 'SMS_174022263'; // 绑定手机验证码模板
            break;
        case 2:
            $templateCode = 'SMS_144450023'; // 登录短信验证码模板
            break;
        case 3:
            $templateCode = 'SMS_144146965'; // 领取优惠券短信验证码模板
            break;
    }
    //短信API产品名（短信产品名固定，无需修改）
    $product = "Dysmsapi";
    //短信API产品域名（接口地址固定，无需修改）
    $domain = "dysmsapi.aliyuncs.com";
    //暂时不支持多Region（目前仅支持cn-hangzhou请勿修改）
    $region = "cn-hangzhou";
    // 初始化用户Profile实例
    $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
    // 增加服务结点
    DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", $product, $domain);
    // 初始化AcsClient用于发起请求
    $acsClient = new DefaultAcsClient($profile);
    // 初始化SendSmsRequest实例用于设置发送短信的参数
    $request = new SendSmsRequest();
    // 必填，设置雉短信接收号码
    $request->setPhoneNumbers($to);
    // 必填，设置签名名称
    $request->setSignName($signName);
    // 必填，设置模板CODE
    $request->setTemplateCode($templateCode);
    // 可选，设置模板参数
    if ($templateParam) {
        $request->setTemplateParam(json_encode($templateParam));
    }

    //发起访问请求
    $acsResponse = $acsClient->getAcsResponse($request);
    //返回请求结果
    $result = json_decode(json_encode($acsResponse), true);
    // 具体返回值参考文档：https://help.aliyun.com/document_detail/55451.html?spm=a2c4g.11186623.6.563.YSe8FK
    return $result;
}

//手机正则验证
function check_phone($phone)
{
    return preg_match("/^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$/", $phone);

}


//生成手机验证码
function create_code()
{
    $key = '';
    $pattern = '1234567890';
    for ($i = 0; $i < 6; $i++) {
        $key .= $pattern[mt_rand(0, 9)];
    }
    return $key;
}


//返回参数
function msg($code = 200, $msg = 'success', $data = [])
{

    return json(['code' => $code, 'msg' => $msg, 'data' => $data], JSON_UNESCAPED_UNICODE);
}


//创建环信账号
function createHuanxinUser($username, $pwd)
{

    $token = getHuanxinToken();


    if ($token['code'] == 200) {

        //请求获取token
        $url = 'https://a1.easemob.com/' . config('api.hx_org_name') . '/' . config('api.hx_app_name') . '/users';
        $data = array(
            'username' => $username,
            'password' => $pwd,
        );

        $headers = array(
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . $token['access_token']
        );

        $res = curl_post($url, $data, $headers);

        $res = json_decode($res, true);


        if (!empty($res['path'])) {

            return array(
                'code' => 200,
                'uuid' => $res['entities'][0]['uuid']
            );
        } else {
            return ['code' => 100, 'error' => '注册失败'];
        }


    } else {
        return $token;
    }


}


//获取环信access_token
function getHuanxinToken()
{

    //从缓存中拿
    $token = cache('huanxin_access_token');


    if ($token) return ['code' => 200, 'access_token' => $token];

    //请求获取token
    $url = 'https://a1.easemob.com/' . config('api.hx_org_name') . '/' . config('api.hx_app_name') . '/token';
    $data = array(
        'grant_type' => 'client_credentials',
        'client_id' => config('api.hx_client_id'),
        'client_secret' => config('api.hx_client_secret'),
    );

    $headers = array(
        'Content-Type' => 'application/json'
    );


    $res = curl_post($url, $data, $headers);

    $res = json_decode($res, true);

    if (!empty($res['access_token'])) {

        //缓存token
        cache('huanxin_access_token', $res['access_token'], 5183900);

        return ['code' => 200, 'access_token' => $res['access_token']];
    } else {
        return ['code' => 100, 'error' => '获取access_token失败'];
    }

}


/**
 * 根据起点坐标和终点坐标测距离
 * @param  [array]   $from    [起点坐标(经纬度),例如:array(118.012951,36.810024)]
 * @param  [array]   $to    [终点坐标(经纬度)]
 * @param  [bool]    $km        是否以公里为单位 false:米 true:公里(千米)
 * @param  [int]     $decimal   精度 保留小数位数
 * @return [string]  距离数值
 */
function get_distance($from, $to, $km = false, $decimal = 0)
{
    sort($from);
    sort($to);
    $EARTH_RADIUS = 6370.996; // 地球半径系数

    $distance = $EARTH_RADIUS * 2 * asin(sqrt(pow(sin(($from[0] * pi() / 180 - $to[0] * pi() / 180) / 2), 2) + cos($from[0] * pi() / 180) * cos($to[0] * pi() / 180) * pow(sin(($from[1] * pi() / 180 - $to[1] * pi() / 180) / 2), 2))) * 1000;

    if ($km) {
        $distance = $distance / 1000;
    }

    return round($distance, $decimal);
}


//获取区域编码
function getAdCode($lng, $lat)
{
    $url = "http://api.map.baidu.com/geocoder/v2/?location=$lat,$lng&output=json&ak=6G472Ak0cDECvD72PjGp2Bxr7sMaOweQ";
    $res = curl_get($url);

    $res = json_decode($res, true);
    return $res;

}


//上传文件
function ossUploadFile($folder, $tmp_name, $ext)
{

//    $oss = new OssClient();
    $oss = new OssClient(config('aliyun.oss.KeyId'), config('aliyun.oss.KeySecret'), config('aliyun.oss.Endpoint'));


    //生成文件名 之后连接上后缀

    $mictime = (explode(' ', microtime()));

    $mtime = strrchr(sprintf("%.2f", $mictime[0]), '.');

    $fileName = $folder . '/' . date('YmdHis', time()) . $mtime . $ext;


    //执行阿里云上传
    $result = $oss->uploadFile(config('aliyun.oss.Bucket'), $fileName, $tmp_name);
    /**
     * 这个只是为了展示
     * 可以删除或者保留下做后面的操作
     */
    $arr = [
        //图片地址
        'imgurl' => $result['info']['url'],
        //数据库保存名称
        'file_name' => $fileName,

    ];

    return $arr;

}


//上传文件
function ossUpload($folder, $tmp_name, $ext)
{

//    $oss = new OssClient();
    $oss = new OssClient(config('aliyun.oss.KeyId'), config('aliyun.oss.KeySecret'), config('aliyun.oss.Endpoint'));

    //生成文件名 之后连接上后缀
    $mictime = (explode(' ', microtime()));

    $mtime = strrchr(sprintf("%.2f", $mictime[0]), '.');

    $fileName = $folder . '/' . date('YmdHis', time()) . $mtime . $ext;

//    $uploadId = $oss->initiateMultipartUpload(config('aliyun.oss.Bucket', '');
    $options = array(
        OssClient::OSS_CHECK_MD5 => true,
        OssClient::OSS_PART_SIZE => 1,
    );


    //执行阿里云上传
    $result = $oss->multiuploadFile(config('aliyun.oss.Bucket'), $fileName, $tmp_name, $options);
    /**
     * 这个只是为了展示
     * 可以删除或者保留下做后面的操作
     */
    $arr = [
        //文件地址
        'url' => $result['info']['url'],
        //数据库保存名称
        'file_name' => $fileName,

    ];

    return $arr;

}


//删除文件
function ossDeleteFile($file_path)
{
    $oss = new OssClient(config('aliyun.oss.KeyId'), config('aliyun.oss.KeySecret'), config('aliyun.oss.Endpoint'));

    $res = $oss->deleteObject(config('aliyun.oss.Bucket'), $file_path);

    return $res;
}


//curl
function curl_get($url, $timeout = 5)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $file_contents = curl_exec($ch);
    curl_close($ch);
    return $file_contents;
}


function curl_post($url, $params = array(), $headers)
{

    $params = json_encode($params);
//    $headers = json_encode($headers);
    $ch = curl_init();//初始化
    curl_setopt($ch, CURLOPT_URL, $url);//抓取指定网页
    curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $data = curl_exec($ch);//运行curl
    curl_close($ch);
    return ($data);
}


function curl_get_https($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.1 Safari/537.11');
    $res = curl_exec($ch);
    $rescode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return $res;
}


